package com.google.code.cakedroid.helper;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.code.cakedroid.base.BaseDataParser;
import com.google.code.cakedroid.core.IOCore;
import com.google.gson.stream.JsonReader;

public class GsonHelper extends BaseDataParser{
	private List<String> keys;
	
	/*
	 * constructor 
	 * Access:private ,only this class can call the method 
	 */
	private GsonHelper(){
		this.fullResult=new ArrayList<Map<String,String>>();
	}
	
	/**
	 * Constructor 
	 * @param keys  initialize variables
	 */
	public GsonHelper(List<String> keys){
		this();
		this.keys=keys;
	}
	
	@Override
	public void parseData(String jsonUrl) {
		this.parseGson(jsonUrl);
	}
	
	/**
	 * Parse json Data
	 * @param jsonUrl
	 */
	private void parseGson(String jsonUrl){	
    	try{
    		Reader streamReader=this.getInputStreamReader(jsonUrl);
    		JsonReader reader = new JsonReader(streamReader);
    		reader.beginArray();
    		while(reader.hasNext()){
    			reader.beginObject();
    			this.subResult=new HashMap<String,String>();
    			while(reader.hasNext()){
    				String tagName = reader.nextName();
    				if(keys.contains(tagName)){
    					this.subResult.put(tagName, reader.nextString());
    				}
    			}
    			reader.endObject();
    			this.fullResult.add(this.subResult);
    		}
    		reader.endArray();
    	}
    	catch(Exception e){
    		e.printStackTrace();
    	}
    }
	
	/*
	 * Get InputStream From given url 
	 * @param jsonUrl  given url address
	 * @return  InputStreamReader
	 * @throws IOException  mostly because of internet problems
	 */
	private Reader getInputStreamReader(String jsonUrl) throws IOException{
		Reader inputStreamReader=new IOCore().getInputStreamReaderFromUrl(jsonUrl);
		return inputStreamReader;
	}
}
